package com.gzsxy.JUC.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * A执行完调用B，B执行完调用C，C执行完调用A
 */
public class C {
    public static void main(String[] args) {
        Data3 data3 = new Data3();
        new Thread(() -> {
            data3.printA();
        }, "A").start();
        new Thread(() -> {
            data3.printB();
        }, "B").start();
        new Thread(() -> {
            data3.printC();
        }, "C").start();
    }


}


class Data3 {  //资源类Lock
    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();
    //1A  2B  3C
    private int number = 1;


    public void printA() {
        lock.lock();
        try {
            //业务，判断->执行 ->通知
            while (number != 1) {
                //等待
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName() + "=>AAAA");
            //唤醒，唤醒指定的人 ，B
            number = 2;
            //通过其他线程我+1完毕
            condition2.signal();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printB() {
        lock.lock();
        try {
            //业务，判断->执行 ->通知
            while (number != 2) {
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName() + "=>BBBBB");
            //唤醒，唤醒指定的人 ，C
            number = 3;
            //通过其他线程我+1完毕
            condition3.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }


    }

    public void printC() {
        lock.lock();
        try {
            //业务，判断->执行 ->通知
            while (number != 3) {
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName() + "=>CCCCCC");
            //唤醒，唤醒指定的人 ，A
            number = 1;
            //通过其他线程我+1完毕
            condition1.signal();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }


    }

}